<?php
session_start();

$cid = $_GET['cid'];
$cn = $_GET['cn'];

include 'dbconnect.php';

  // Check connection
if (mysqli_connect_errno())
  {
  //echo "alert'Failed to connect to MySQL: ' . mysqli_connect_error()";
  }
$number = $_SESSION['number'];
if ($number[0] == "+")
	$number[0] = "_";

$table = "SELECT * FROM contacts".$number;
$result = mysqli_query($con, $table);
$count = 0;

while($row = mysqli_fetch_array($result))
  {
  
  if ($row['contactId']==$cid){
    $sql="UPDATE `contacts$number` SET `view` = '1' WHERE `contacts$number`.`contactId` = '$cid';";

     if (!mysqli_query($con,$sql))
     {
          echo('Error: ' . mysqli_error($con));
     } 
	 $count++;
	break;
  }
  }
  
  if ($count==0)
  {
	$sql="INSERT `contacts$number` VALUES (null, '$cn', '$cn', 1, '$cid');";

     if (!mysqli_query($con,$sql))
     {
          echo('Error: ' . mysqli_error($con));
     } 
  }
  echo $cid;
mysqli_close($con);
?>
